import axios from 'axios'
import $router from '../router/index'
import type {InternalAxiosRequestConfig,AxiosResponse} from "axios";
//实例化axios对象
var service = axios.create({
    timeout: 10 * 1000,
    baseURL: 'http://118.178.238.19:3001',//基准路径
})
//设置请求拦截器
service.interceptors.request.use(
    (config:InternalAxiosRequestConfig) => {
        // console.log('service.interceptors.request'); //执行了
        //设置请求头参数(携带请求头参数)
        // config.headers.token = "Bearer" + ' ' + sessionStorage.getItem('token');
        let token = sessionStorage.getItem("token")
        if(token){
            config.headers.token=token
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
)
//设置响应拦截器
service.interceptors.response.use(
    (res:AxiosResponse) => {
        return res;
    },
    (error) => {
        if (error.response.status == 401) {
            alert('登陆过期!');
            //删除token,跳转到登录页
            // console.log(1);
            $router.push('/Login')
        }
         else if (error.response.status == 404) {
            alert('访问路径有误!')
        }
        else if (error.response.status == 500) {
            alert('服务器内部错误!')
        }
        return Promise.reject(error)
        
    },
)
// 默认导出实例
export default service;